package com.wisdytech.linkdcs.factory.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.configuration.dao.ITtEqConfigurationDao;
import com.wisdytech.linkdcs.configuration.model.TtEqConfiguration;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationService;
import com.wisdytech.linkdcs.factory.dao.TmAreaDao;
import com.wisdytech.linkdcs.factory.dao.TmFactoryDao;
import com.wisdytech.linkdcs.factory.dao.TmProductionLineDao;
import com.wisdytech.linkdcs.factory.dao.TmShopDao;
import com.wisdytech.linkdcs.factory.model.Area;
import com.wisdytech.linkdcs.factory.model.Factory;
import com.wisdytech.linkdcs.factory.model.ProductionLine;
import com.wisdytech.linkdcs.factory.model.Shop;
import com.wisdytech.linkdcs.factory.service.TmFactoryService;
import com.wisdytech.linkdcs.factory.service.TmProductionLineService;
import com.wisdytech.linkdcs.factory.service.TmShopService;
import com.wisdytech.linkdcs.system.model.SysOperation;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.system.vo.TreeviewNodeVO;

/**
 * <p>
 * ClassName: TmFactoryServiceImpl
 * <p>
 * Description: 厂区管理的业务实现类
 * </p>
 * <p>
 * Author: chenbin
 * </p>
 * <p>
 * Date: 2018年5月3日
 * </p>
 */
@Service("tmFactoryService")
@Transactional
public class TmFactoryServiceImpl extends BaseService<TmFactoryDao, Factory> implements TmFactoryService{
    /**
     * 注入厂区管理dao
     */
	@Resource
	private TmFactoryDao tmFactoryDao;
    /**
     * 注入产线管理dao
     */
	@Resource
	private TmProductionLineDao tmProductionLineDao;
    /**
     * 注入车间管理dao
     */
	@Resource
	private TmShopDao tmShopDao;
    /**
     * 注入区域管理dao
     */
	@Resource
	private TmAreaDao tmAreaDao;
    /**
     * 注入组态管理dao
     */
	@Resource
	private ITtEqConfigurationDao ttEqConfigurationDao;
	
	@Resource
	private ITtEqConfigurationService ttEqConfigurationService;
	
	@Resource
	private TmShopService tmShopService;
	
	@Resource
	private TmProductionLineService tmProductionLineService;
	
	@Override
	public PageInfo<Factory> listFactoryByFilter(String factoryCode, String factoryName, Filter filter) {
        EntityWrapper<Factory> ewFactory = new EntityWrapper<>();
        if (StringUtils.isNotBlank(factoryCode)) {
        	ewFactory.like("FACTORY_CODE", factoryCode);
        }
        if (StringUtils.isNotBlank(factoryName)) {
        	ewFactory.like("FACTORY_NAME", factoryName);
        }
        ewFactory.orderBy("create_date", false);
        List<Factory> list = super.beforeList(TmFactoryDao.class, filter)
                .selectList(ewFactory.eq("del_flag", CommonConstants.DEL_FLAG));
        PageInfo<Factory> factoryPage = new PageInfo<>(list);
        return factoryPage;
	}

	@Override
	public boolean addFactory(Factory factory, String loginName) {
		EntityWrapper<Factory> ew = new EntityWrapper<>();
        //验证厂区编码的唯一性
        List<Factory> factoryList = new ArrayList<>();
        factoryList = tmFactoryDao.selectPage(new Page<SysUser>(1, 1), ew.eq("FACTORY_CODE", factory.getFactoryCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!factoryList.isEmpty()) {
        	throw new ServiceException("该厂区编码被使用");
        }
        
        factory.setPkId(BaseUtil.getUUID());
        factory.setDelFlag(CommonConstants.DEL_FLAG);
        factory.setCreateUser(loginName);
        factory.setCreateDate(new Date());
        int operationCount = tmFactoryDao.insert(factory);
        if (operationCount <= 0) {
            throw new ServiceException("新增失败");
        }
        return true;
	}

	@Override
	public boolean updateFactory(Factory factory, String loginName) {
		EntityWrapper<Factory> ew = new EntityWrapper<>();;
        //验证工序编码的唯一性--修改功能
		List<Factory> factoryList;
		factoryList = tmFactoryDao.selectPage(new Page<SysOperation>(1, 1),ew.eq("FACTORY_CODE", factory.getFactoryCode()).ne("pk_id", factory.getPkId()));
        if (factoryList.size() > 0){
        	throw new ServiceException("该厂区编码被使用");
        }
        factory.setUpdateDate(new Date());
        factory.setUpdateUser(loginName);
        int operationCount = tmFactoryDao.updateFactoryById(factory);
        if (operationCount <= 0) {
            throw new ServiceException("修改失败");
        }
        return true;
	}

	@Override
	public boolean delFactoryById(String ids) {
        List<String> idList = new ArrayList<String>();
        String[] id = ids.split(",");
        for (int i = 0; i < id.length; i++) {
            idList.add(id[i]);
        }
        for (String pkId : id) {
        	//通过厂区的id查询所有产线
            List<ProductionLine> factoryList = tmProductionLineDao.listAllProductionLineByFactoryId(pkId);
            if (!factoryList.isEmpty()) {
            	throw new ServiceException("所选记录中存在“车间”");
            }
            //通过厂区的id查询所有车间
            List<Shop> shopList = tmShopDao.listAllShopByFactoryId(pkId);
            if (!shopList.isEmpty()) {
            	throw new ServiceException("所选记录中存在“车间”");
            }
            //通过厂区的id查询所有区域
            List<Area> areaList = tmAreaDao.listAllAreaByFactoryId(pkId);
            if (!areaList.isEmpty()) {
            	throw new ServiceException("所选记录中存在“区域”");
            }
            //通过厂区的id查询所有厂区组态图
            EntityWrapper<TtEqConfiguration> ew = new EntityWrapper<>();
            ew.eq("del_flag", CommonConstants.DEL_FLAG).eq("location_id", pkId).eq("type", "1");
            int count = this.ttEqConfigurationDao.selectCount(ew);
            if(count>0) {
            	throw new ServiceException("所选记录中存在组态图关联");
            }
            
        }
        
        int factoryCount = tmFactoryDao.deleteBatchIds(idList);
        if (factoryCount <= 0) {
            throw new ServiceException("删除失败");
        }
        return true;
	}

	@Override
	public Factory getFactoryById(String pkId){
		if(StringUtils.isEmpty(pkId)) {
			return new Factory();
		}
		return tmFactoryDao.selectById(pkId);
	}

	@Override
	public List<Factory> listAllFactory(String search) {
        EntityWrapper<Factory> ew = new EntityWrapper<>();
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        return tmFactoryDao.selectList(ew);
	}

	@Override
	public List<TreeviewNodeVO> getFactoryTree() {
		List<TreeviewNodeVO> root =new ArrayList<>();
		List<Factory> factorys =
				listAllFactory("");
		for(Factory  factory : factorys) {
			TreeviewNodeVO factoryNodes =factory2Node(factory);
			List<TreeviewNodeVO> leaf =new ArrayList<>();
			
			
			//获取所有的产线 车间
			List<Shop> shops =tmShopService.listAllShops(factory.getPkId());
			for(Shop shop :shops) {
				leaf.add(shop2Node(shop, factory.getPkId()));
			}
			List<ProductionLine>  lines =tmProductionLineService.listAllLine(factory.getPkId());
			for(ProductionLine line :lines) {
				leaf.add(line2Node(line, factory.getPkId()));
			}
			
			factoryNodes.setNodes(leaf);
			root.add(factoryNodes);
		}
		
		return root;
	}
	
	private TreeviewNodeVO factory2Node(Factory  factory) {
		TreeviewNodeVO node = new TreeviewNodeVO();
		node.setId(factory.getPkId());
		node.setText(factory.getFactoryName());
		List<String> tags =new ArrayList<>();
		tags.add(factory.getFactoryName());
		node.setTags(tags);
		return node;
	}
	
	private TreeviewNodeVO shop2Node(Shop  shop,String parentId) {
		TreeviewNodeVO node = new TreeviewNodeVO();
		node.setId(shop.getPkId());
		node.setText(shop.getShopName());
		node.setParentId(parentId);
		List<String> tags =new ArrayList<>();
		tags.add(shop.getShopName());
		node.setTags(tags);
		return node;
	}
	private TreeviewNodeVO line2Node(ProductionLine  line,String parentId) {
		TreeviewNodeVO node = new TreeviewNodeVO();
		node.setId(line.getPkId());
		node.setText(line.getLineName());
		node.setParentId(parentId);
		List<String> tags =new ArrayList<>();
		tags.add(line.getLineName());
		node.setTags(tags);
		return node;
	}

}
